﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase.Config;
using System.Configuration;

namespace UFrameWork
{
    /// <summary>
    /// 服务器监听类
    /// </summary>
    public class UServer : AppServer<USession>
    {
        /// <summary>
        /// 监听端口
        /// </summary>
        public int Port;

        /// <summary>
        /// 启动服务器
        /// </summary>
        /// <param name="port">端口号</param>
        public UServer(int port)
            : base(new DefaultReceiveFilterFactory<UReceiveFilter,StringRequestInfo>())
        {
            Port = port;
            try
            {
                int maxConnect = 0;
                int.TryParse(ConfigurationManager.AppSettings.Get("MaxConnectionNumber"), out maxConnect);
                if (maxConnect <= 0) maxConnect = 10000;
                ServerConfig config = new ServerConfig()
                {
                    Port = port,
                    MaxConnectionNumber = maxConnect,
                    MaxRequestLength    = 1024 * 1024,
                };

                if (!Setup(config) || !Start())
                {
                    UWork.Do(UEvent.SERVER_START_FAIL, this, "启动失败");
                    return;
                }
            }
            catch (Exception e)
            {
                UWork.Do(UEvent.SERVER_START_FAIL, this,e.Message);
                ULog.Error(e);
                return;
            }

            UWork.Do(UEvent.SERVER_START_SUCCESS,this);

            NewSessionConnected += new SessionHandler<USession>(OnNewSessionConnected);
            SessionClosed += new SessionHandler<USession, CloseReason>(OnSessionClosed);
        }

        /// <summary>
        ///新会话连接
        /// </summary>
        private void OnNewSessionConnected(USession session)
        {
            UWork.Do(UEvent.SERVER_SESSION_NEW, session);
        }

        /// <summary>
        /// 会话断开
        /// </summary>
        private void OnSessionClosed(USession session, CloseReason reason)
        {
            UWork.Do(UEvent.SERVER_SESSION_CLOSE, session, reason);
        }
    }
}